<template>
    <div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="50px">

            <el-form-item label="网关" prop="gatewayId">
                <gateway-select @changeGateway="changeGateway"/>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:loop:add']"
                >新增
                </el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-row v-show="loopList.length>0" v-loading="loading" :gutter="20" style="margin-top: 10px;font-size: 15px" type="flex" justify="space-around"
                v-for="(item,index) in loopList" :key="index">
            <el-col :xl="24">
                <el-card shadow="always">
                    <div slot="header" class="clearfix">
                        <span style="font-size: 14px;color: #6c7077;font-weight: 700">{{ item.loopName }}</span>
                        <el-button
                            style="float: right; padding: 3px 0"
                            type="text"
                            @click="handleUpdate(item)"
                            v-hasPermi="['business:loop:edit']"
                        >修改
                        </el-button>
                    </div>
                    <div style="display: flex;align-items: center;color:#717783">
                        <span>设备类型：</span>
                        <dict-tag2 :type="DICT_TYPE.DEVICE_TYPE" :value="item.deviceType"/>
                    </div>

                    <div v-if="item.deviceType===5">
                        <div style="display: flex;align-items: center;color:#717783;margin-top: 10px;">
                            <span>网关名称：</span>
                            <span>{{ item.gatewayName }}</span>
                        </div>


                        <div style="display: flex;align-items: center;margin-top: 10px;color:#717783 ">
                            <span>站号：</span>
                            <span>{{ item.siteNumber }}</span>
                        </div>
                        <div style="display: flex;align-items: center;margin-top: 10px;color:#717783 ">
                            <span>位置：</span>
                            <span>{{ item.position }}</span>
                        </div>

                        <div style="display: flex;align-items: center;margin-top: 10px;color:#717783 ">
                            <span>数值：</span>
                            <span>{{ item.loopValue }}</span>
                        </div>

                        <div style="display: flex;align-items: center;margin-top: 10px;color:#717783 ">
                            <span>工作模式：</span>
                            <span v-if="item.loopWorkType==='1'">普通</span>
                            <span v-if="item.loopWorkType==='0'">脉冲</span>
                        </div>
                    </div>

                    <div style="display: flex;align-items: center;margin-top: 10px;color:#717783 ">
                        <span>设备状态：</span>
                        <div>
                            <svg-icon v-if="item.serverOnline === '1'" icon-class="wifi-online"
                                      style="width: 3em; height: 3em;"
                            />
                            <svg-icon v-if="item.serverOnline === '0'" icon-class="wifi-offline"
                                      style="width: 3em; height: 3em;"
                            />
                        </div>
                    </div>

                    <div style="margin-top: 10px">
                        <el-button
                            size="mini"
                            @click="handleDelete(item)"
                            type="danger"
                            v-hasPermi="['business:sensor:remove']"
                        >删除
                        </el-button>
                        <el-button @click="manualTest(item,index)" size="mini"
                        >高级
                        </el-button>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <el-row v-show="loopList.length<1" v-loading="loading" :gutter="20" style="margin-top: 10px;" type="flex" justify="space-around">
            <el-col :xl="24">
                <el-empty></el-empty>
            </el-col>
        </el-row>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改控制点对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body v-dialogDrag :close-on-click-modal ="false">

            <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">

                <el-form-item label="设备类型" prop="deviceType">
                    <el-select v-model="form.deviceType" placeholder="请选择设备类型" clearable>
                        <el-option v-for="dict in deviceTypeDictDatas" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)"/>
                    </el-select>
                </el-form-item>
                <!--                电表-->
                <div v-if="form.deviceType===0">
                    <el-form-item label="电表" prop="deviceId">
                        <el-select v-model="form.deviceId"
                                   placeholder="请选择设备"
                        >
                            <el-option
                                v-for="item in electricityListOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="名称" prop="loopName">
                        <el-input v-model="form.loopName" placeholder="请输入控制点名称"/>
                    </el-form-item>
                </div>
                <!--                网关-->
                <div v-if="form.deviceType===5">
                    <el-form-item label="网关" prop="gatewayId">
                        <el-select v-model="form.gatewayId"
                                   placeholder="请选择网关"
                        >
                            <el-option
                                v-for="item in gatewayListOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="大类型" prop="loopType">
                        <el-radio-group v-model="form.loopType">
                            <el-radio-button label="1">数值型</el-radio-button>
                            <el-radio-button label="0">开关型</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="小类型" prop="loopTypeId">
                        <el-cascader
                            v-model="form.loopTypeId"
                            :options="loopTypeList"
                            :props="{emitPath:false}"
                        ></el-cascader>
                    </el-form-item>

                    <el-form-item label="名称" prop="loopName">
                        <el-input v-model="form.loopName" placeholder="请输入控制点名称"/>
                    </el-form-item>

                    <el-form-item label="站号" prop="siteNumber">
                        <el-input v-model="form.siteNumber" placeholder="请输入站号"/>
                    </el-form-item>

                    <el-form-item label="位置" prop="position">
                        <el-input v-model="form.position" placeholder="请输入寄存器位置"/>
                    </el-form-item>
                </div>

                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number v-model="form.orderNum" :min="0"></el-input-number>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">{{ buttonText }}</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>

        </el-dialog>

        <el-dialog title="设置" :visible.sync="testOpen" width="500px" append-to-body :close-on-click-modal ="false">
            <LoopSet :loop="form" :key="form.loopId" @refresh="refreshFunc"/>
            <el-form label-width="40px">
                <el-form-item label="快捷">
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button type="success" size="small" @click="prev">上一个</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="success" size="small" @click="next">下一个</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
import { pageListLoop, getLoop, delLoop, addLoop, updateLoop } from '@/api/equipment/loop'

import {
    listLoopType
} from '@/api/business/loopType'

import gatewaySelect from "@/views/common/GatewaySelect.vue";
import '@/utils/directives.js'

import LoopSet from '../set'

const common = require('@/api/common/common')
import { getElectricity, getElectricMeterSelect2 } from '@/api/equipment/electricity'
import { getDictDatas, DICT_TYPE } from '@/utils/dictNew'
export default {
    name: 'Loop',
    components: {
        gatewaySelect,
        LoopSet
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 控制点表格数据
            loopList: [],
            // 弹出层标题
            title: '',
            buttonText: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                loopName: null,
                loopType: null,
                loopWorkType: null,
                loopValue: null,
                position: null,
                siteNumber: null,
                gatewayId: null,
                loopOrderNumber: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                // gatewayId: [
                //     { required: true, message: '请选择网关', trigger: 'blur' }
                // ],
                loopName: [
                    { required: true, message: '请输入控制点名称', trigger: 'blur' }
                ],
                loopType: [
                    { required: true, message: '请选择控制点类型', trigger: 'blur' }
                ],
                // siteNumber: [
                //     { required: true, message: '请输入站号', trigger: 'blur' }
                // ],
                // position: [
                //     { required: true, message: '请输入寄存器位置', trigger: 'blur' }
                // ],
                deviceType: [
                    { required: true, message: '请输入选择设备类型', trigger: 'blur' }
                ],
            },
            // 接收websocket返回的消息
            receiveObj: null,
            gatewayList: [],
            testOpen: false,

            // 用于修改回显所属网关
            gatewayListOption: [],
            electricityListOption: [],


            messageObj: {},
            currentIndex: null,
            loopTypeList: [],
            // 数据字典
            deviceTypeDictDatas: getDictDatas(DICT_TYPE.DEVICE_TYPE)
        }
    },
    created() {
        this.getLoopTypeList()
        this.getElectricitySelectData()
    },
    methods: {
        // 获取下拉电表
        getElectricitySelectData(){
            getElectricMeterSelect2().then(res=>{
                this.electricityListOption = res.data
            })
        },
        /**
         * 获取所有控制点类型
         */
        getLoopTypeList() {
            this.loopTypeList = []
            listLoopType().then(response => {

                // console.log(response)

                for (let item of response.data) {
                    if (item.parentId === 0) {
                        let level1 = {
                            value: item.id,
                            label: item.typeName,
                            children: []
                        }
                        this.loopTypeList.push(level1)
                    }
                }

                for (let item of response.data) {
                    let obj = this.loopTypeList.find((level1) => {
                        return level1.value === item.parentId
                    })
                    if (obj !== undefined) {
                        let level2 = {
                            value: item.id,
                            label: item.typeName
                        }
                        obj.children.push(level2)
                    }
                }

            })
        },

        // 接收子组件传递的消息
        changeGateway(obj) {
            this.gatewayListOption = obj.gatewayListOption
            // this.queryParams.projectId = obj.projectId
            this.queryParams.gatewayId = obj.gatewayId
            this.getList()
        },

        calculateIndex(index) {
            const pageNum = this.queryParams.pageNum
            const pageSize = this.queryParams.pageSize
            return index + 1 + (pageNum - 1) * pageSize
        },

        getList() {
            this.loading = true
            pageListLoop(this.queryParams).then(response => {
                this.loopList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        cancel() {
            this.open = false
            this.reset()
        },

        reset() {
            this.form = {
                loopId: null,
                loopName: null,
                loopType: null,
                loopWorkType: null,
                orderNum: 0,
                loopValue: '0',
                position: null,
                siteNumber: null,
                gatewayId: null,
                loopOrderNumber: null,
                deviceType:null,
                deviceId:null,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.loopId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加控制点'
            this.buttonText = '添 加'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const loopId = row.loopId || this.ids
            getLoop(loopId).then(response => {
                this.form = response.data
                this.open = true
                this.title = '修改控制点'
                this.buttonText = '修 改'
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.loopId != null) {
                        updateLoop(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addLoop(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const loopIds = row.loopId || this.ids
            this.$modal.confirm('是否确认删除控制点编号为"' + loopIds + '"的数据项？').then(function() {
                return delLoop(loopIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('business/loop/export', {
                ...this.queryParams
            }, `loop_${new Date().getTime()}.xlsx`)
        },

       async manualTest(row, index) {
            if(row.deviceType===0){
             await  getElectricity(row.deviceId).then(response => {
                    row.switchStatus = response.data.switchStatus
                })
            }
            this.currentIndex = index
            this.testOpen = true
            this.form = row
            this.currentGatewayNumber = row.gatewayNumber
        },

        prev() {
            if (this.currentIndex > 0) {
                this.currentIndex--
            } else {
                this.$message.warning('已经是第一个了')
            }

            let data = this.loopList[this.currentIndex]

            this.form = data

            this.form.loopNewValue = null

            this.currentGatewayNumber = data.gatewayNumber
        },
        next() {
            if (this.currentIndex < this.loopList.length - 1) {
                this.currentIndex++
            } else {
                this.$message.warning('已经是最后一个了')
            }

            let data = this.loopList[this.currentIndex]

            this.form = data

            this.form.loopNewValue = null

            this.currentGatewayNumber = data.gatewayNumber
        },
        refreshFunc(obj) {
            this.getList()
        }
    }
}
</script>

<style>
.textColor{
    color: #717783;
}
</style>
